package com.nav.util;

public class BigDecimal extends java.math.BigDecimal {
	private static final long serialVersionUID = 1L;
	public BigDecimal(String s) {
		super(s);
	}
	private BigDecimal(java.math.BigDecimal b) {
		super(b.toString());
	}
	private BigDecimal commonPrefix(java.math.BigDecimal l, java.math.BigDecimal h) {
		String cp = commonPrefix(l.toString(), h.toString());
		return new BigDecimal(cp.length() <= 0 ? "0" : cp);
	}
	private String commonPrefix(String l, String h) {
		char[] la = l.toCharArray(), ha = h.toCharArray();
		int i = 0;
		while(i < l.length() && i < h.length() && la[i] == ha[i])
			i++;
		return l.substring(0, i);
	}
	public BigDecimal sqrt(int numDec) {
		java.math.BigDecimal l = BigDecimal.ZERO, h = this, two = new java.math.BigDecimal(2), m = l.add(h).divide(two);
		BigDecimal cp = commonPrefix(l, h);
		while(cp.scale() < numDec) {
			java.math.BigDecimal m2 = m.multiply(m);
			int c = m2.compareTo(this);
			if(c < 0)
				l = m;
			else if(c == 0)
				new BigDecimal(m); // got the answer
			else
				h = m;
			m = l.add(h).divide(two);
			cp = commonPrefix(l, h);
		}
		return cp; // got the precision
	}
}
